const ArticleModel = require('../model/article')
// 专门做首页响应
module.exports = {
    async index(ctx, next) {
        // 获取文章数据
        const pageSize = 5
        const currentPage =Number( ctx.query.page) || 1
        // 类型
        let cid
        const query = cid ? { category: cid } : {}
        const allArticleCount = await ArticleModel.find(query).count()
        const pageCount = Math.ceil(allArticleCount / pageSize)
        const pageStart = currentPage - 2 > 0 ? currentPage - 2 : 1
        const pageEnd = pageStart + 4 >= pageCount ? pageCount : pageStart + 4
        let articles = await ArticleModel.find(query).sort({ _id: -1 }).skip((currentPage - 1) * pageSize).limit(pageSize)

        let pagination = []
        if (pageCount >= 3) {
            if (Number(currentPage) === 1) {
                pagination.push(1, 2, 3)
            } else if (Number(currentPage) === pageCount && pageCount >= 3) {
                pagination.push(Number(currentPage) - 2, Number(currentPage) - 1, Number(currentPage))
            } else if (Number(currentPage) < pageCount && pageCount >= 3) {
                pagination.push(Number(currentPage) - 1, Number(currentPage), Number(currentPage) + 1)
            }
        } else if (pageCount >= 2 && Number(currentPage) < pageCount) {
            pagination.push(Number(currentPage), Number(currentPage) + 1)
        } else {
            pagination.push(currentPage)
        }

        const baseUrl = `${ctx.path}?page=`
        // Koa的render函数，去读取模板文件(可以写html语法的文件)
        await ctx.render('index', {
            title: 'My Bolg',
            articles,
            pageSize,
            currentPage,
            allArticleCount,
            pageCount,
            pageStart,
            pageEnd,
            baseUrl,
            pagination
        })
        // console.log(allArticleCount);
        // console.log(articles);   
    }
}